<template>
	<view class="page-wrapper">
		<view class="chat-container card">
			<scroll-view scroll-y class="chat-list" @scrolltoupper="scrollToUpper" :scroll-into-view="scrollIntoView"
				:scroll-with-animation="true">
				<view class="message-item animate-fade-in" v-for="(item, index) in messageList" :key="index"
					:class="[item.role, {'loading': item.loading}]" :id="'msg-' + index">
					<image v-if="item.role === 'system'" class="avatar" src="/static/images/tylm.png"></image>
					<image v-if="item.role === 'user'" class="avatar" src="/static/logo.png"></image>
					<view class="message-content">
						<text>{{item.content}}</text>
						<view v-if="item.loading" class="loading-dots">
							<text>.</text><text>.</text><text>.</text>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="input-area">
			<input type="text" v-model="inputContent" placeholder="请输入您的问题" confirm-type="send" @confirm="sendMessage"
				:disabled="isLoading" />
			<button class="send-btn" @click="sendMessage" :disabled="!inputContent.trim() || isLoading">
				<uni-icons :type="isLoading ? 'spinner-cycle' : 'paperplane'" size="24" color="#ffffff"></uni-icons>
			</button>
		</view>
	</view>
</template>


<script>
	const API_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
	const API_URL = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation'; // 正确的API端点

	export default {
		data() {
			return {
				inputContent: '',
				messageList: [{
					role: 'system',
					content: '你好！我是化学AI助手。我可以帮你解答化学相关的问题，比如：化学方程式、元素周期表、化学反应原理等。请问有什么我可以帮你的吗？'
				}],
				scrollIntoView: '',
				isLoading: false
			}
		},
		onLoad() {
			// 删除冗余代码
		},
		methods: {
			scrollToUpper() {
				console.log('到顶了')
			},
			async sendMessage() {
				if (!this.inputContent.trim() || this.isLoading) return

				// 添加用户消息
				this.messageList.push({
					role: 'user',
					content: this.inputContent
				})

				// 添加一个加载中的AI消息
				this.messageList.push({
					role: 'system',
					content: '',
					loading: true
				})

				// 保存用户输入并清空输入框
				const userInput = this.inputContent
				this.inputContent = ''

				// 滚动到最新消息
				this.scrollToLatest()

				// 设置加载状态
				this.isLoading = true

				try {
					const response = await this.callAlibabaAPI(userInput)

					// 更新最后一条消息（移除加载状态）
					this.messageList.pop()
					this.messageList.push({
						role: 'system',
						content: response
					})
				} catch (error) {
					// 处理错误情况
					this.messageList.pop()
					this.messageList.push({
						role: 'system',
						content: '抱歉，处理您的请求时出现了错误。请稍后再试。'
					})
					console.error('API调用错误:', error)
				} finally {
					this.isLoading = false
					this.scrollToLatest()
				}
			},
			async callAlibabaAPI(message) {
				// try {
				//   const response = await uni.request({
				//     url: API_URL,
				//     method: 'POST',
				//     header: {
				//       'Content-Type': 'application/json',
				//       'Authorization': `DashScope ${API_KEY}` // 正确的认证格式
				//     },
				//     data: {
				//       model: 'qwen-max', // 模型名称
				//       prompt: message // 使用 prompt 参数
				//     }
				//   })

				//   if (response.statusCode === 200) {
				//     return response.data.output.text; // 根据实际返回结构调整
				//   } else {
				//     throw new Error('API请求失败');
				//   }
				// } catch (error) {
				//   throw error
				// }

				try {
					const response = await uni.request({
						url: "http://192.168.43.74:3000/chat",
						method: 'POST',
						header: {
							'Content-Type': 'application/json',
						},
						data: {
							messages: this.messageList
						}
					})

					if (response.statusCode === 200) {
						console.log(response);
						if (response.data.code === 200) {
							// this.messageList.push({
							// 	role: 'system',
							// 	content: response.data.response,
							// 	loading: true
							// })
							return response.data.response
						}else{
							throw new Error('API请求失败');
						}
						// return response.data.output.text; // 根据实际返回结构调整
					} else {
						throw new Error('API请求失败');
					}
				} catch (error) {
					throw error
				}

			},
			scrollToLatest() {
				this.$nextTick(() => {
					this.scrollIntoView = 'msg-' + (this.messageList.length - 1)
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	page {
		height: 100%;
		background-color: #ebf5fb;
	}

	/* #ifdef H5 */
	.page-wrapper {
		height: calc(100vh - 44px - 50px);
		display: flex;
		flex-direction: column;
		background-color: #ebf5fb;
		padding: 15rpx;
		box-sizing: border-box;
	}

	/* #endif */

	/* #ifndef H5 */
	.page-wrapper {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #ebf5fb;
		padding: 15rpx;
		padding-bottom: calc(15rpx + env(safe-area-inset-bottom));
		box-sizing: border-box;
	}

	/* #endif */

	.chat-container {
		flex: 1;
		overflow: hidden;
		position: relative;
		border-radius: 20rpx;
		background-color: #fff;
		box-shadow: 0 5rpx 20rpx rgba(52, 152, 219, 0.1);
		margin-bottom: 20rpx;
		display: flex;
		flex-direction: column;
	}

	.chat-list {
		flex: 1;
		height: 100%;
		padding: 15rpx;
		box-sizing: border-box;
	}

	.message-item {
		display: flex;
		margin-bottom: 20rpx;
		align-items: flex-start;
	}

	.message-item.user {
		flex-direction: row-reverse;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin: 0 20rpx;
		flex-shrink: 0;
		box-shadow: 0 2rpx 10rpx rgba(52, 152, 219, 0.1);
	}

	.message-content {
		max-width: 70%;
		padding: 16rpx 24rpx;
		border-radius: 18rpx;
		word-break: break-all;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		line-height: 1.5;
		font-size: 28rpx;
		white-space: pre-wrap;
		word-wrap: break-word;
	}

	.message-item.ai .message-content {
		background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
		color: #fff;
		border-top-left-radius: 4rpx;
	}

	.message-item.user .message-content {
		background-color: #fff;
		color: #333;
		border-top-right-radius: 4rpx;
		border: 1px solid #ebf5fb;
	}

	.input-area {
		padding: 15rpx 0;
		display: flex;
		align-items: center;
		position: relative;
		z-index: 1;
		background-color: #ebf5fb;
	}

	.input-area input {
		flex: 1;
		height: 80rpx;
		background-color: #fff;
		border-radius: 40rpx;
		padding: 0 30rpx;
		margin-right: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(52, 152, 219, 0.1);
		border: 1px solid #ebf5fb;
	}

	.send-btn {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
		color: #fff;
		border-radius: 50%;
		padding: 0;
		margin: 0;
		box-shadow: 0 6rpx 15rpx rgba(52, 152, 219, 0.3);
		transition: all 0.3s ease;

		&:active {
			transform: translateY(3rpx);
			box-shadow: 0 3rpx 8rpx rgba(52, 152, 219, 0.2);
		}

		&[disabled] {
			background: #bdc3c7;
			box-shadow: none;
		}
	}

	.iconfont.icon-send {
		font-size: 38rpx;
	}

	@keyframes messageAnimation {
		from {
			opacity: 0;
			transform: translateY(10rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.message-item {
		animation: messageAnimation 0.3s ease-out forwards;
	}

	.message-item.loading .message-content {
		opacity: 0.7;
	}

	.loading-dots {
		display: inline-flex;
		align-items: center;
		height: 20rpx;

		text {
			animation: loadingDots 1.4s infinite;
			font-size: 24rpx;

			&:nth-child(2) {
				animation-delay: 0.2s;
			}

			&:nth-child(3) {
				animation-delay: 0.4s;
			}
		}
	}

	@keyframes loadingDots {

		0%,
		100% {
			opacity: 0.2;
			transform: translateY(0);
		}

		50% {
			opacity: 1;
			transform: translateY(-4rpx);
		}
	}

	.send-btn {
		&.loading {
			animation: rotating 2s linear infinite;
		}
	}

	@keyframes rotating {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}
</style>